<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\controller\admin\AdminBaseController;
use app\model\admin\SysUser as SysUserModel;
use app\model\admin\SysRole as SysRoleModel;
use app\model\admin\SysUserRole as SysUserRoleModel;
use think\facade\Db;
use think\Request;

class SysUser extends AdminBaseController
{
     /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $field = "*";
        $data = SysUserModel::scope('where', $request->param())
            ->scope('dataFilter')
            ->field($field)
            ->with(['dept'])
            ->order('id','desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        return successPage($data);
    }

    public function show(Request $request){
        $id = $request->param('id', 0);
        $data = SysUserModel::where('id', $id)->scope('dataFilter')->find();

        $roles = SysRoleModel::where('status', '1')->scope('dataFilter')->select();

        $user_role_ids = SysUserRoleModel::where('user_id',$id)->column('role_id');
        return success([
            'user' => $data,
            'roles' => $roles,
            'roleIds' => $user_role_ids
        ]);
    }


    public function save(Request $request){
        $param = $request->param();
        
        if(isset($param['id'])){
            unset($param['id']);
        }
        
        $roleIds = $param['roleIds'] ?? [];
        if(empty($roleIds)){
            return error('请分配角色');
        }
        Db::startTrans();
        $msg = 'success';
        try {
            $data = SysUserModel::create($param);
            if($data->id > 0){
                $user_id = $data->id;
                Db::table('sys_user_role')->where('user_id', $user_id)->delete();
                $add_datas = [];
                foreach ($roleIds as $role_id){
                    $add_datas[] = [
                        'user_id' => $user_id,
                        'role_id' => $role_id,
                    ];
                }
                Db::table('sys_user_role')->insertAll($add_datas);
            }
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([],"新增成功") : error($msg);
    }

    public function update(Request $request){
        $param = $request->except(['password','login_ip','login_time','create_by']);
        $id = $param['id'];
        if(isset($param['id'])){
            unset($param['id']);
        }
        
        $roleIds = $param['roleIds'] ?? [];
        if(empty($roleIds)){
            return error('请分配角色');
        }

        $model = SysUserModel::where('id', $id)->scope('dataFilter')->find();

        Db::startTrans();
        $msg = 'success';
        try {
            $ret = $model->save($param);
            if($ret){
                Db::table('sys_user_role')->where('user_id', $id)->delete();
                $add_datas = [];
                foreach ($roleIds as $role_id){
                    $add_datas[] = [
                        'user_id' => $id,
                        'role_id' => $role_id,
                    ];
                }
                Db::table('sys_user_role')->insertAll($add_datas);
                
            }
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([],"更新成功") : error($msg);
    }
    public function changeStatus(Request $request){
        $id = $request->param('id');
        $status = $request->param('status','');
        if(!$id || $status == ''){
            return error('缺少必要参数');
        }
        
        $model = SysUserModel::where('id', $id)->scope('dataFilter')->find();

        $data = $request->only(['status']);
    
        $ret = $model->save($data);
        if(!$ret){
            return error('更新失败');
        }
        return success();
    }

    public function resetPwd(Request $request){
        $id = $request->post('id');
        $password = $request->post('password');

        $user = SysUserModel::where('id', $id)->scope('dataFilter')->find();
        if(!$user){
            return error('数据不存在');
        }
        $user->password = trim($password);
        $user->save();

        return success([],'更新成功');
    }

    public function delete(Request $request)
    {
        $id = $request->param('id', '');
        if(!$id){
            return error('缺少必要参数');
        }
        
        $ids = explode(',', $id);
        if(in_array(1,$ids)){
            return error('包含不可删除数据');
        }

        Db::startTrans();
        $msg = 'success';
        try {
            $ret = SysUserModel::destroy($ids);
            DB::table('sys_user_role')->whereIn('user_id', $ids)->delete();
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([],"删除成功") : error($msg);
    }

    public function profile(Request $request){
        $id = $request->create_by;
        $data = SysUserModel::with(['dept','roles'])->where('id', $id)->find();
        $roleGroup = $data->roles()->column('role_name');
        return success([
            'user' => $data,
            'roleGroup' => implode(',', $roleGroup)
        ]);
    }

    public function updateProfile(Request $request)
    {
        $id = $request->create_by;
        if(!$id){
            return error('缺少必要参数');
        }
        
        $data = $request->only(['nickname','email','phone','sex']);
        $data['update_by'] = $id;
        $data['update_time'] = time();

        $ret = Db::table('sys_user')->where('id', $id)->update($data);

        if(!$ret){
            return error('更新失败');
        }
        return success();
    }

    public function updatePwd(Request $request)
    {
        $id = $request->create_by;
        if(!$id){
            return error('缺少必要参数');
        }
        
        $param = $request->only(['oldPassword','newPassword']);
        $oldPassword = $param['oldPassword'];
        $newPassword = $param['newPassword'];
        if(!$oldPassword || !$newPassword){
            return error('缺少必要参数');
        }
        $model = SysUserModel::find($id);
        if($model->password != md5($oldPassword)){
            return error('旧密码不正确');
        }

        $data = [];
        $data['update_by'] = $id;
        $data['update_time'] = time();
        $data['password'] = md5($newPassword);

        $ret = Db::table('sys_user')->where('id', $id)->update($data);

        if(!$ret){
            return error('更新失败');
        }
        return success();
    }

}
